/*
 * appRtc.c
 *
 *  Created on: 2018年1月2日
 *      Author: Administrator
 *      说明:RTC采用格林威治标准时间,以1970年1月1日0时0分0秒作为时间基数
 */

/***** Includes *****/
/* OS */
/*************************************************************
* 	include 
* 	???	
*************************************************************/
#include <string.h>
#include <stdio.h>

/*   MCU_LIB_include    */
#include "gd32e230.h"

/* OS ????? */
#include "osInclude.h"
/*   MCU_BSP_include      */
#include "bspTimer.h"
#include "bspUART.h"
#include "bspDataFlash.h"
/* user_include */
#include "appTask.h"
#include "UserConfig.h"
#include "appCoreProtoco.h"
#include "appRoomProtocol.h"
#include "appRtc.h"



static uint8_t ucgRtcTaskStack[RTC_TASK_STACK_SIZE];


//获取当前需用运行秒-需考虑溢出情况
#define bIsLeapusYear(x)    ((x%4 == 0) && (x%100 != 0 || x%400 == 0))
static volatile uint32_t    uigNteTime=1577808000;//初始时间戳为2020.01.01.00:00:00


/*设备时间戳更新*/
void vDeviceTimestampRunning(void)
{
	uigNteTime ++;
}

/* 获取设备时间戳*/
uint32_t uiGetDeviceTimestamp(void)
{
    return uigNteTime;
}



void vTimeSync(uint32_t uiNtp)
{
    DEBUG_PRINTF("Ntp:%d\r",uiNtp);
	uigNteTime = uiNtp;
}

static uint8_t ucCaculateWeekDay(uint16_t usYear,uint8_t ucMonth, uint8_t ucDay)
{
    uint8_t ucWeek;
    if(ucMonth==1||ucMonth==2)
    {
        ucMonth += 12;
        usYear --;
    }
    ucWeek=(   ucDay +
               2*ucMonth +
               3*(ucMonth+1)/5 +
               usYear +
               usYear/4 -
               usYear/100 +
               usYear/400   )%7 + 1;
    return ucWeek;
}

/* 获取一年的天数 */
static uint16_t usGetYearDays(uint16_t usYear)
{
    if(bIsLeapusYear(usYear))
        return 366;
    return 365;
}

void vGetTime(tsTime *ptTime, uint32_t uiNtpTime)
{
    uint32_t uiTime,i;
    uint8_t ucMons[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

    uiTime = uiNtpTime + EASTERN_8TH;   /* 从NTP时间转为北京时间(东8区) */

    ptTime->usYear = uiTime/FOUR_YEAR_SEC;              /* 计算有多少周期 */
    uiTime -= ptTime->usYear*FOUR_YEAR_SEC;             /* 计算剩余时间 */
    ptTime->usYear = 4*ptTime->usYear + BASE_YEAR;      /* 得到一个整周期的4年 */
    while(1)
    {
        i = usGetYearDays(ptTime->usYear)*DAY_SEC;		/* 计算一年有多少秒 */
        if(uiTime >= i)
        {
            uiTime -= i;
            ptTime->usYear++;
        }
        else
        {
            break;
        }
    }

    if(bIsLeapusYear(ptTime->usYear))
        ucMons[1]=29;
    else
        ucMons[1]=28;
    for(i=0; ; )
    {
        if(uiTime >= ucMons[i]*DAY_SEC)
        {
            uiTime -= ucMons[i]*DAY_SEC;
            i++;
        }
        else
        {
            break;
        }
    }
    ptTime->ucMonth = i+1; /* 月 */

    ptTime->ucDay= uiTime/DAY_SEC + 1;  /* 日 */
    uiTime %= DAY_SEC;

    ptTime->ucHour = uiTime/3600;
    ptTime->ucMinute = (uiTime%3600)/60;
    ptTime->ucSecond = uiTime%60;
    ptTime->ucWeek = ucCaculateWeekDay(ptTime->usYear,ptTime->ucMonth,ptTime->ucDay);
}









